package zhouzhouyongche.service.impl;

import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import zhouzhouyongche.client_util.ErrorCode;
import zhouzhouyongche.dao.PassengerDao;
import zhouzhouyongche.dao.UserDao;
import zhouzhouyongche.model.Passenger;
import zhouzhouyongche.model.User;
import zhouzhouyongche.service.PassengerService;

@Service
public class PassengerServiceImpl implements PassengerService {

	@Autowired
	private PassengerDao passengerDao;
	
	@Autowired
	private UserDao userDao;

	@Override
	public int deletePassenger(int passengerId) {
		return passengerDao.deletePassenger(passengerId);
	}

	//passenger存在则进行修改，不存在则插入，以passengerIdNumber为依据判断passenger是否存在
	@Override
	public int savePassenger(int userId, String passengerName, String passengerIdNumber) {
		boolean bRes = true;
		boolean bAdd = true;
		User user = userDao.get(userId);
		Set<Passenger> passengers = user.getPassengers();
		for (Passenger p : passengers) {
			if (p.getIdNumber().equals(passengerIdNumber)) {
				p.setPassengerName(passengerName);
				bAdd = false;
			}
		}
		if (bAdd) {
			Passenger passenger = new Passenger();
			passenger.setTicketType(1); //成人票
			passenger.setPassengerName(passengerName);
			passenger.setIdNumber(passengerIdNumber);
			passengerDao.save(passenger);
			
			user.getPassengers().add(passenger);
		}
		
		try{
			userDao.save(user);
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			bRes = false;
		}
		return bRes ? ErrorCode.SUCCESS : ErrorCode.ERROR_PASSENGER_SAVE;
	}

	@Override
	public List<Passenger> getPassenger(int userId) {
		return passengerDao.getPassenger(userId);
	}
	
}
